import { useState, useMemo } from "react";

// 一个模拟的昂贵计算函数
const longtimeFun = (num: number) => {
	console.log("触发计算函数" , num);
	for (let i = 0; i < 1000000000; i++) {} // 模拟计算时间
	return num * 2;
};

function StudyUseMome() {
	const [count, setCount] = useState(0);
	const [inputValue, setInputValue] = useState("");
	// 只有 count 改变时，longtimeFun 才会重新计算
	const resCount = useMemo(() => longtimeFun(count), [count]);
	return (
		<div>
			<h2>3. Study useMemo </h2>
			<div>
				<p>Count: {count}</p>
				<button onClick={() => setCount(count + 1)}>增加 Count</button>
			</div>

			<div>
				<input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)}/>
				<p>Input value: {inputValue}</p>
			</div>
			<div>
				<p>最终 Result: {resCount}</p>
			</div>
		</div>
	);
}

export default StudyUseMome;
